package com.microservice.salmon.oauth.service.rbac.impl;

import com.microservice.salmon.db.entities.SysMenu;
import com.microservice.salmon.db.entities.SysRole;
import com.microservice.salmon.db.entities.SysUser;
import com.microservice.salmon.db.mapper.SysMenuMapper;
import com.microservice.salmon.db.mapper.SysRoleMapper;
import com.microservice.salmon.db.mapper.SysUserMapper;
import com.microservice.salmon.oauth.service.rbac.SysRbacService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * <p>
 * RBAC 模型实现类
 * </p>
 *
 * @author 王洪庆 2018-10-30 21:52
 */
@Service
public class AdminRbacServiceImpl implements SysRbacService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysMenuMapper menuMapper;

    @Override
    @Cacheable(cacheNames = "role_info", key = "#userId", unless = "#result.size() == 0")
    public List<SysRole> getRoleByUserId(int userId) {
        return roleMapper.getRoleByUserId(userId);
    }

    @Override
    public List<SysRole> getRoleByUsername(String username) {
        return roleMapper.getRoleByUsername(username);
    }

    @Override
    @Cacheable(cacheNames = "user_info", key = "#username", unless = "#result == null")
    public SysUser getUserInfoByUsername(String username) {
        // 创建Example
        Example example = new Example(SysUser.class);
        // 创建Criteria
        Example.Criteria criteria = example.createCriteria();
        // 添加条件
        criteria.andEqualTo("loginName", username);
        return userMapper.selectOneByExample(example);
    }

    @Override
    @Cacheable(cacheNames = "menu_role", key = "#roleId", unless = "#result.size() == 0")
    public List<SysMenu> getMenuInfoByRoleId(int roleId) {
        return menuMapper.getMenuInfoByRoleId(roleId);
    }
}
